#include "List.h"

LTNode* BuyLTNode(LTypeData x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL)
	{
		perror("fail malloc");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}
LTNode* LTInit1()
{
	LTNode* phead = BuyLTNode(-1);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}
void LTInit2(LTNode** pphead)
{
	LTNode* plist = NULL;
	plist = BuyLTNode(-1);
	plist->next = plist;
	plist->prev = plist;
    *pphead = plist;
}

void LTDestory(LTNode* phead)
{
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		LTNode* plist = cur->next;
		free(cur);
		cur = plist;
	}
	free(phead);
}


void LTPrint(LTNode* phead)
{
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}

void LTPushBack(LTNode* phead, LTypeData x)
{
	assert(phead);
	LTNode* newnode = BuyLTNode(x);
	LTNode* tail = phead->prev;

	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;
}
void LTPopBack(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	LTNode* tail = phead->prev;
	LTNode* prevtail = tail->prev;  

	prevtail->next = phead;
	phead->prev = prevtail;
	free(tail);
}

void PushFront(LTNode* phead, LTypeData x)
{
	assert(phead);
	LTNode* newnode = BuyLTNode(x);
	newnode->next = phead->next;
	phead->next->prev = newnode;
	phead->next = newnode;
	newnode->prev = phead;
}

void LTPopFront(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	
	LTNode* plist = phead->next;
	LTNode* netplist = plist->next;

	phead->next = netplist;
	netplist->prev = phead;
	free(plist);
}

LTNode* LTFind(LTNode* phead, LTypeData x)
{
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
		{return cur; }
		cur = cur->next;
	}
	return NULL;
}

void LTInsert(LTNode* pos, LTypeData x)
{
	LTNode* prevpos = pos->prev;
	LTNode* newnode = BuyLTNode(x);

	prevpos->next = newnode;
	newnode->prev = prevpos;
	newnode->next = pos;
	pos->prev = newnode;
}

void LTErase(LTNode* pos)
{
	assert(pos);
	LTNode* prev = pos->prev;
	LTNode* next = pos->next;
	prev->next = next;
	next->prev = prev;
	free(pos);
}

void LTPushBackPlus(LTNode* phead, LTypeData x)
{
	assert(phead);
	LTInsert(phead, x);
}
void PushFrontPlus(LTNode* phead, LTypeData x)
{
	assert(phead);
	LTInsert(phead->next, x);
}

void  LTPopBackPlus(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	LTErase(phead->prev);
}
void LTPopFrontPlus(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	LTErase(phead->next);
}

bool LTEmpty(LTNode* phead)
{
	assert(phead);
	return phead->next == phead;
}

size_t LTSzie(LTNode* phead)
{
	assert(phead);
	size_t size = 0;
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		size++;
		cur = cur->next;
	}
	return size;
}
